<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\integrate\Ticket;
use app\admin\model\User;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\admin\model\Branch;
use think\Exception;

/**
 * 员工管理
 *
 * @icon fa fa-circle-o
 */
class Staff extends Base
{
    protected $noNeedRight = ['*'];
    /**
     * Staff模型对象
     * @var \app\admin\model\Staff
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Staff;

        $position = [
            '无' => '无',
            '支行行长' => '支行行长',
            '主管' => '主管',
            '分理处负责人' => '分理处负责人',
            '副行长' => '副行长',
            '大堂经理' => '大堂经理',
            '员工'=>'员工'
        ];
        $this->assign('position',$position);
    }

    /**
     * 查看
     */
    public function index()
    {
        $param = $this->request->param();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $style = $this->request->get("style", null);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('style',$style)
                ->with([
                    'branch' => function($query){
                        $query->field('id,name');
                    },
                    /*'admin' => function($query){
                        $query->field('id,nickname as name');
                    }*/
                ])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list->items() as &$item){
                if($item->branch){
                    $item->bank_name = $item->branch->name;
                }else{
                    $item->bank_name = '无';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assign('style',$param['style']);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $param = $this->request->param();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                /*if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $pid = Admin::where('id',$this->auth->id)->value('id');
                    $params[$this->dataLimitField] = $pid;
                }*/
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $obj = $this->model->where('mobile',$params['mobile'])->find();
                    if($obj) $this->error('手机号已存在');
                    if(empty($params['password'])){
                        $params['password'] = substr($params['mobile'],5,6);
                    }
                    $params['salt']     = Random::alnum();
                    $params['password'] = Auth::instance()->getEncryptPassword($params['password'],$params['salt']);
                    $result    = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('style',$param['style']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        /*$adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }*/
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $obj = $this->model->where('mobile',$params['mobile'])->where('id','<>',$ids)->find();
                    if($obj) $this->error('手机号已存在');
                    if(!empty($params['password'])){
                        $params['salt']     = Random::alnum();
                        $params['password'] = Auth::instance()->getEncryptPassword($params['password'],$params['salt']);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $count = Ticket::where('staff_id',$ids)->count();
            if($count > 0){
                $this->error('账号使用中，无法删除');
            }
            $pk = $this->model->getPk();
            /*$adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }*/
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    if($v->user_id != 0)
                    {
                        User::where('id',$v->user_id)->update(['group_id',1]);
                    }
                }


                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function import(){
        if ($this->request->isPost()) {
            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            // 2. 解析Excel（假设第一行为表头，从第二行开始是数据）
            $spreadsheet = IOFactory::load($filePath);
            $sheet = $spreadsheet->getActiveSheet();
            $data = $sheet->toArray(null, false, true, true); // 转为数组
            array_shift($data); // 移除表头

            // 新增：过滤空行（关键步骤）
            $data = array_filter($data, function($row) {
                // trim处理避免空格导致的误判
                $name = trim($row['A'] ?? '');
                return !empty($name);
            });
            // 重置数组索引（可选，避免后续foreach的index混乱）
            $data = array_values($data);
            if (empty($data)) {
                return $this->error('Excel中无有效数据行');
            }

            // 3. 提取所有支行名称并去重（同时清洗名称）
            $branchNames = [];
            foreach ($data as $row) {
                $branchName = trim($row['A']); // 假设B列是支行名称
                $branchNames[$branchName] = $branchName; // 去重
            }
            $branchNames = array_keys($branchNames);

            // 4. 处理支行：建立“名称→ID”映射（存在则复用，不存在则创建）
            $branchMap = [];
            foreach ($branchNames as $name) {
                try {
                    // 优先用“名称+编号”匹配（若有编号），这里简化为名称匹配
                    $branch = Branch::where('name', $name)->where('admin_id',$this->auth->id)->find();
                    if ($branch) {
                        $branchMap[$name] = $branch->id;
                    } else {
                        // 创建新支行（其他字段按需补充，如code、address等）
                        $newBranch = Branch::create(['name' => $name,'admin_id'=>$this->auth->id]);
                        $branchMap[$name] = $newBranch->id;
                    }
                } catch (Exception $e) {
                    $this->error("处理支行[{$name}]失败：{$e->getMessage()}");
                }
            }

            // 5. 处理员工：绑定支行ID（事务保证原子性）
            $employees = [];
            $salt = Random::alnum();
            foreach ($data as $index => $row) {
                $branchName = trim($row['A']);
                // 校验支行是否已在映射中（理论上不会出现，防止异常）
                if (!isset($branchMap[$branchName])) {
                    $this->error("第".($index+2)."行：支行[{$branchName}]未匹配，请检查名称");
                }
                // 组装员工数据（假设A列是员工姓名）
                $password_data = $row['E'];
                $mobile = trim($row['D']);
                $name   = trim($row['C']);
                $wkno   = trim($row['B']);
                if(empty($mobile) || empty($name) || empty($wkno)){
                    $this->error("第".($index+2)."行：参数不能为空");
                }
                //检测手机号是否存在
                $staff = $this->model->where('mobile',$mobile)->find();
                if($staff){
                    $this->error("第".($index+2)."行：手机号[{$mobile}]已存在，请修改手机号");
                }
                if(empty($password_data)){
                    $password = Auth::instance()->getEncryptPassword(substr($mobile,-6),$salt);
                }else{
                    $password = Auth::instance()->getEncryptPassword(trim($password_data),$salt);
                }
                $employees[] = [
                    'mobile'=>$mobile,
                    'name' => $name,
                    'branch_id' => $branchMap[$branchName],
                    'style'=>2,
                    'wkno'=>$wkno,
                    'salt'=>$salt,
                    'password'=>$password,
                    'admin_id'=>$this->auth->id,
                    'createtime'=>time()
                ];
            }

            // 6. 批量插入员工（事务回滚防止部分成功）
            try {
                Db::startTrans();
                $this->model::insertAll($employees);
                Db::commit(); // 提交事务
                $this->success('导入成功');
            } catch (Exception $e) {
                Db::rollback(); // 回滚事务
                $this->error("导入员工失败：{$e->getMessage()}");
            }
        }
        return $this->fetch('staff');
    }

}
